<template>
  <div class="form-table">
    <el-form ref="ruleForm" status-icon :model="form" :rules="tableRules">
      <el-table
        border
        ref="table"
        v-bind="$attrs"
        :data="form.tableData"
        empty-text="暂无数据"
        :height="$attrs.height"
        :max-height="maxTableHeightVal"
        @selection-change="handleSelectionChange"
      >
        <template v-if="form.theadData.length>0">
          <el-table-column
            v-if="selectionThead.length>0"
            type="selection"
            :align="selectionThead[0].align?selectionThead[0].align:''"
            :width="selectionThead[0].width?selectionThead[0].width:'55px'"
            :fixed="selectionThead[0].fixed!==undefined?selectionThead[0].fixed:true"
          ></el-table-column>
          <el-table-column
            v-if="indexThead.length>0"
            type="index"
            :align="indexThead[0].align?indexThead[0].align:''"
            :width="indexThead[0].width?indexThead[0].width:'55px'"
            :label="indexThead[0].label?labelName(indexThead[0].label):null"
            :fixed="indexThead[0].fixed!==undefined?indexThead[0].fixed:true"
            :index="tableIndexMethod"
          ></el-table-column>
          <el-table-column
            :label="item.label"
            v-for="(item,index) in theadFieldsData"
            :key="index"
            :align="item.align?item.align:'center'"
            :width="item.width?item.width:'auto'"
            :fixed="item.prop==='operation'?(item.fixed?item.fixed:'right'):false"
          >
            <template slot-scope="scope">
              <el-form-item
                v-if="item.prop!=='operation'"
                :prop="`tableData.${scope.$index }.${item.prop}`"
                :rules="getTableRules(scope.$index,item.prop)"
              >
                <el-input
                  :class="item.align?item.align:'center'"
                  v-if="item.type==='input'&&item.dataType==='Number'"
                  v-model.number="scope.row[item.name]"
                  :readonly="operationType === 'readonly'?true:(scope.row.readonly!==undefined?scope.row.readonly:(item.readonly!==undefined?item.readonly:false))"
                  :disabled="operationType === 'readonly'?true:(scope.row.disabled!==undefined?scope.row.disabled:(item.disabled!==undefined?item.disabled:false))"
                  clearable
                  @focus="item.focus&&(Object.prototype.toString.call(item.focus)==='[object Function]')?item.focus($event,item,scope.$index,scope.row):null"
                  @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item,scope.$index,scope.row):null"
                ></el-input>
                <el-input
                  :class="item.align?item.align:'center'"
                  v-if="item.type==='input'&&item.dataType!=='Number'"
                  v-model="scope.row[item.name]"
                  :readonly="operationType === 'readonly'?true:(scope.row.readonly!==undefined?scope.row.readonly:(item.readonly!==undefined?item.readonly:false))"
                  :disabled="operationType === 'readonly'?true:(scope.row.disabled!==undefined?scope.row.disabled:(item.disabled!==undefined?item.disabled:false))"
                  clearable
                  @focus="item.focus&&(Object.prototype.toString.call(item.focus)==='[object Function]')?item.focus($event,item,scope.$index,scope.row):null"
                  @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item,scope.$index,scope.row):null"
                ></el-input>
                <el-select
                  style="width:100%"
                  :class="item.align?item.align:'center'"
                  popper-class="form-table-select"
                  v-if="item.type === 'select'"
                  v-model="scope.row[item.name]"
                  :disabled="operationType === 'readonly'?true:(scope.row.disabled!==undefined?scope.row.disabled:(item.disabled!==undefined?item.disabled:false))"
                  :placeholder="item.placeholder?placeholder('select',item.placeholder):null"
                  v-loading="item.loading!==undefined?item.loading:false"
                  autocomplete
                  clearable
                  @focus="item.focus&&(Object.prototype.toString.call(item.focus)==='[object Function]')?item.focus($event,item,scope.$index,scope.row):null"
                  @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item,scope.$index,scope.row):null"
                >
                  <template v-if="item.selectType!==undefined&&item.selectType==='item'">
                    <el-option
                      v-for="(item1,index1) in scope.row[item.selectTypeName]"
                      :key="index1"
                      :label="labelName(item1.label)"
                      :value="item1.value"
                      :disabled="item1.disabled===undefined?false:item1.disabled"
                    ></el-option>
                  </template>
                  <template v-else>
                    <el-option
                      v-for="(item1,index1) in item.selectOptions"
                      :key="index1"
                      :label="labelName(item1.label)"
                      :value="item1.value"
                      :disabled="item1.disabled===undefined?false:item1.disabled"
                    ></el-option>
                  </template>
                </el-select>
                <el-date-picker
                  v-if="item.type === 'daterange'"
                  v-model="scope.row[item.name]"
                  type="daterange"
                  range-separator="-"
                  :start-placeholder="$t('el.datepicker.startDate')"
                  :end-placeholder="$t('el.datepicker.endDate')"
                  :readonly="operationType==='readonly'?true:(scope.row.readonly!==undefined?scope.row.readonly:false)"
                  :disabled="scope.row.disabled?scope.row.disabled:false"
                  :picker-options="item.pickerOptions!==undefined?item.pickerOptions:null"
                />
                <el-date-picker
                  v-if="item.type === 'date'"
                  v-model="scope.row[item.name]"
                  type="date"
                  :readonly="operationType==='readonly'?true:(scope.row.readonly!==undefined?scope.row.readonly:false)"
                  :disabled="scope.row.disabled?scope.row.disabled:false"
                  :picker-options="item.pickerOptions!==undefined?item.pickerOptions:null"
                  :placeholder="$t('el.datepicker.selectDate')"
                ></el-date-picker>
                <el-date-picker
                  v-if="item.type === 'datetime'"
                  v-model="scope.row[item.name]"
                  type="datetime"
                  :readonly="operationType==='readonly'?true:(scope.row.readonly!==undefined?scope.row.readonly:false)"
                  :placeholder="$t('el.datepicker.selectDate')"
                  :disabled="scope.row.disabled?scope.row.disabled:false"
                  :picker-options="item.pickerOptions!==undefined?item.pickerOptions:null"
                ></el-date-picker>
                <el-date-picker
                  v-if="item.type === 'datetimerange'"
                  v-model="ruleForm[item.name]"
                  type="datetimerange"
                  :readonly="operationType==='readonly'?true:(scope.row.readonly!==undefined?scope.row.readonly:false)"
                  :disabled="scope.row.disabled?scope.row.disabled:false"
                  :picker-options="item.pickerOptions!==undefined?item.pickerOptions:null"
                  :placeholder="$t('el.datepicker.selectDate')"
                ></el-date-picker>
              </el-form-item>
              <div class="flex justify-center align-center" v-if="item.prop==='operation'">
                <el-button
                  v-if="item.options.edit"
                  @click="edit(scope.row)"
                  size="mini"
                  style="color:#409EFF;"
                  :title="$t('i18n_edit')"
                >
                  <i class="el-icon-edit"></i>
                </el-button>
                <el-button
                  v-if="item.options.more"
                  @click="more(scope.row)"
                  size="mini"
                  style="color:#409EFF;"
                  :title="$t('i18n_edit')"
                >
                  更多
                  <i class="el-icon-more"></i>
                </el-button>
                <el-button
                  v-if="item.options.delete"
                  @click="del(scope.row)"
                  size="mini"
                  style="color:red;"
                  :title="$t('i18n_delete')"
                >
                  <i class="el-icon-delete-solid"></i>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </el-form>
  </div>
</template>

<script>
import _ from 'lodash'
import Cookies from 'js-cookie'
export default {
  props: {
    tableIndexMethod: { //
      type: Function
    },
    operationType: {
      type: String,
      default: 'edit'
    },
    dynamicRuleName: { // 动态改变触发校验的字段
      type: String,
      default: ''
    },
    dynamicRuleNameValue: { // 动态改变触发校验的字段对应的值
      type: String,
      default: ''
    },
    dynamicTargetRuleName: { // 动态改变触发校验的目标字段
      type: String,
      default: ''
    },
    maxTableHeight: { // 动态改变触发校验的目标字段
      type: String,
      default: 'auto'
    },
    rules: {
      type: Object,
      default: () => {
        return {}
      }
    },
    form: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      tableRuleOptions: {}
    }
  },
  computed: {
    tableRules () {
      if (this.form.tableData.length > 0) {
        this.form.theadData.forEach((item) => {
          if (this.rules[item.prop] !== undefined) {
            this.form.tableData.forEach((item1, key1) => {
              if (this.rules[item.prop].validator !== undefined) {
                this.tableRuleOptions[`tableData.${key1}.${item.prop}`] = JSON.parse(JSON.stringify(this.rules[item.prop]))
                this.tableRuleOptions[`tableData.${key1}.${item.prop}`].validator = this.rules[item.prop].validator
              } else {
                this.tableRuleOptions[`tableData.${key1}.${item.prop}`] = JSON.parse(JSON.stringify(this.rules[item.prop]))
              }

              if (this.dynamicRuleName && item1[this.dynamicRuleName] && item1[this.dynamicRuleName] === this.dynamicRuleNameValue) { // 比如dynamicRuleName='chargeUnitCode'时需要校验 dynamicTargetRuleName='basicChargeProjectId'字段
                if (this.tableRuleOptions[`tableData.${key1}.${this.dynamicTargetRuleName}`] !== undefined) {
                  this.$set(this.tableRuleOptions[`tableData.${key1}.${this.dynamicTargetRuleName}`], 'required', true)
                }
              }
            })
          }
        })
      }
      return this.tableRuleOptions
    },
    indexThead () { // 序号列
      return this.form.theadData.filter((item) => {
        return item.prop === 'index'
      })
    },
    selectionThead () { // 选择列
      return this.form.theadData.filter((item) => {
        return item.prop === 'selection'
      })
    },
    theadFieldsData () { // 字段列
      const fieldsData = this.form.theadData.filter((item) => {
        return item.prop !== 'selection' && item.prop !== 'index'
      })
      return (this.indexThead.length > 0 || this.selectionThead.length > 0) ? fieldsData : this.form.theadData
    },
    maxTableHeightVal () {
      return this.maxTableHeight === 'auto' ? this.$attrs.height : this.maxTableHeight
    }
  },
  created () {

  },
  methods: {
    setTableItemRules (index, prop, key, value) { // 设置行内对应的校验值
      this.$set(this.tableRuleOptions[`tableData.${index}.${prop}`], key, value)
    },
    getTableRules (index, prop) { // 获取当前的校验选项
      return this.tableRuleOptions[`tableData.${index}.${prop}`]
    },
    placeholder (type, data) {
      if (data.indexOf('.') !== -1) {
        if (type === 'select') {
          return data ? (this.$t('el.select.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('el.select.placeholder')
        }
        if (type === 'input') {
          return data ? (this.$t('input.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('input.placeholder')
        }
        if (type === 'daterange' || type === 'date') {
          return data ? (this.$t('input.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('input.placeholder')
        }
      } else if (data.indexOf('i18n') !== -1) {
        const str = this.$utils.getLabelName(data, this)
        if (Cookies.get('lang') === 'en') {
          if (type === 'select') {
            return this.$t('el.select.placeholder') + ' ' + str
          }
          if (type === 'input') {
            return this.$t('input.placeholder') + ' ' + str
          }
          if (type === 'select') {
            return this.$t('el.select.placeholder') + ' ' + str
          }
        } else {
          if (type === 'select') {
            return this.$t('el.select.placeholder') + str
          }
          if (type === 'input') {
            return this.$t('input.placeholder') + str
          }
          if (type === 'select') {
            return this.$t('el.select.placeholder') + str
          }
        }
      } else {
        return data
      }
    },
    labelName (data) { // 多语言切换
      if (data !== undefined) {
        if (data.indexOf('.') !== -1) {
          return this.$t(data)
        } else if (data.indexOf('i18n') !== -1) {
          return this.$utils.getLabelName(data, this)
        } else {
          return data
        }
      } else {
        return ''
      }
    },
    handleSelectionChange (val) {
      this.$emit('selectionChange', val)
    },
    submit () {
      let submitData = false
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const table = JSON.parse(JSON.stringify(this.form.tableData))
          const selectTypeNames = this.form.theadData.map((item) => {
            return item.selectTypeName
          })
          if (table.length > 0) {
            table.map((item) => {
              Object.keys(item).forEach(key => {
                if (key !== undefined && selectTypeNames.includes(key)) {
                  delete item[key]
                }
                if (key === 'startTime-endTime') {
                  item.startTime = this.$utils.formatDateTime(item[key][0])
                  item.endTime = this.$utils.formatDateTime(item[key][1])
                  delete item[key]
                }
              })
            })
          }
          submitData = table
        }
      })
      if (Object.prototype.toString.call(submitData) === '[object Array]' && submitData.length === 0) {
        submitData = false
      }
      return submitData
    },
    edit (item) {
      this.$emit('edit', item)
    },
    del (item) {
      this.$emit('del', item)
    },
    more (item) {
      this.$emit('more', item)
    }
  }
}
</script>

<style scoped lang="scss">
.form-table {
  overflow: hidden;

  .el-form {
    .el-form-item {
      margin-top: 20px;
      margin-bottom: 20px;
    }
  }
  .el-table {
    &/deep/ td {
      padding-top: 0 !important;
      padding-bottom: 0 !important;
    }
    &/deep/ .el-form-item__content {
      .el-input,
      .el-select {
        &.center {
          .el-input__inner {
            text-align: center !important;
          }
        }
        &.left {
          .el-input__inner {
            text-align: left !important;
          }
        }
        &.right {
          .el-input__inner {
            text-align: right !important;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
</style>
